<script setup lang='ts'>
import { fetchEventSource } from '@microsoft/fetch-event-source'
import markdownit from 'markdown-it'

const md = markdownit({
  html: true,
  breaks: true,
  typographer: true,
})
const route = useRoute()
const router = useRouter()
const answer = ref('')
const scrollContainer = ref()
function scrollToBottom() {
  if (scrollContainer.value) {
    window.scrollTo({ top: scrollContainer.value.scrollHeight })
  }
}
const afteranswer = computed(() => {
  return md.render(answer.value)
})
const showthink = ref(true)
const { counter, reset, pause, resume } = useInterval(1000, { controls: true, immediate: false })
const abortController = ref<AbortController | null>(null) // 新增中止控制器
const baseURL = import.meta.env.VITE_BASE_HOST
async function getData() {
  abortController.value?.abort() // 先中止之前的请求
  const ctrl = new AbortController()
  abortController.value = ctrl // 存储新的控制器
  resume()
  await fetchEventSource(`${baseURL}/chat/sendMessage2`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ conversationId: 100, message: route.query.q }),
    signal: ctrl.signal,
    onopen: (response) => {
      if (!response.ok) {
        $message.error(`消息发送失败:${response.statusText}`)
      }
    },
    onmessage(ev) {
      // console.log('decodedData', Base64.decode(ev.data))
      answer.value += ev.data.replace(/\n/g, '<br />')
      nextTick(() => {
        scrollToBottom()
      })
      // console.log(ev.data)
    },
    onclose: () => {
      pause()
      // console.log('Connection closed')
    },
    onerror: (error) => {
      pause()
      // console.error('Error occurred:', error)
    },
  })
}
watch(() => route.query.q, () => {
  if (route.path !== '/answer')
    return
  abortController.value?.abort() // 路由变化时中止当前请求
  reset()
  answer.value = ''
  showthink.value = true
  getData()
})

onMounted(() => {
  getData()
})
</script>

<template>
  <div ref="scrollContainer" class="pt-36">
    <div class="absolute absolute left-5 top-5 flex-center cursor-pointer gap-x-2 px-5 py-3 text-primary" @click="router.back">
      <div class="i-typcn-arrow-back text-70px" />
      <div class="text-36px">返回</div>
    </div>
    <div class="mb-10 ml-40 b rounded-2xl bg-primary bg-opacity-10 p-5 text-36px text-primary">
      {{ route.query.q }}
    </div>
    <div class="mb-5 flex-center inline-flex cursor-pointer b rounded-lg p-3 text-28px text-gray" @click="showthink = !showthink">
      <div class="">已深度思考（用时{{ counter }}秒）</div>
      <div class="text-32px" :class="[showthink ? 'i-ep-arrow-down' : 'i-ep-arrow-up']" />
    </div>
    <div :class="[{ showthink }]" class="answer pb-120 text-justify text-32px leading-10">
      <div v-html="afteranswer" />
    </div>
  </div>
</template>

<style>
think {
  font-size: 30px;
  display: block;
  color: #999;
  padding: 20px 20px;
  display: none;
  border-radius: 10px;
  border: 1px solid #eee;
  margin-bottom: 20px;
  background: #f9f9f9;
  text-align: justify;
}

.showthink think {
  /* height: 0px; */
  line-height: 1.5;
  display: block;
  overflow: hidden;
}

p {
  margin: 5px 0;
  line-height: 2;
}
</style>

<route lang='yaml'>
meta:
  title: 'deepseek'
</route>
